"""
实时协作编辑器

提供多用户同步编辑、冲突检测和解决、协作状态管理功能
"""

import logging
import json
import asyncio
import threading
import time
import uuid
from typing import Dict, List, Optional, Any, Set, Callable, Tuple
from dataclasses import dataclass, field
from enum import Enum
import datetime
from collections import defaultdict, deque
import hashlib

from ..models.base_models import BaseModel
from .base_component import BaseComponent

logger = logging.getLogger(__name__)


class OperationType(Enum):
    """操作类型"""
    INSERT = "insert"                        # 插入文本
    DELETE = "delete"                        # 删除文本
    REPLACE = "replace"                      # 替换文本
    FORMAT = "format"                        # 格式化
    MOVE = "move"                           # 移动内容
    CURSOR = "cursor"                       # 光标移动
    SELECTION = "selection"                 # 选择文本


class ConflictResolution(Enum):
    """冲突解决策略"""
    LAST_WRITE_WINS = "last_write_wins"     # 最后写入获胜
    FIRST_WRITE_WINS = "first_write_wins"   # 首次写入获胜
    MERGE = "merge"                         # 智能合并
    USER_CHOICE = "user_choice"             # 用户选择
    AUTOMATIC = "automatic"                 # 自动解决


class UserRole(Enum):
    """用户角色"""
    OWNER = "owner"                         # 文档所有者
    EDITOR = "editor"                       # 编辑者
    REVIEWER = "reviewer"                   # 审阅者
    VIEWER = "viewer"                       # 查看者


class SessionStatus(Enum):
    """会话状态"""
    ACTIVE = "active"                       # 活跃
    IDLE = "idle"                          # 空闲
    DISCONNECTED = "disconnected"           # 断开连接
    RECONNECTING = "reconnecting"           # 重连中


@dataclass
class Operation(BaseModel):
    """操作对象"""
    operation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    user_id: str = ""
    session_id: str = ""
    operation_type: OperationType = OperationType.INSERT
    
    # 操作位置和内容
    position: int = 0                       # 操作位置
    length: int = 0                         # 操作长度
    content: str = ""                       # 操作内容
    old_content: str = ""                   # 原始内容
    
    # 时间戳和版本
    timestamp: datetime.datetime = field(default_factory=datetime.datetime.now)
    version: int = 0                        # 文档版本
    parent_version: int = 0                 # 父版本
    
    # 元数据
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'operation_id': self.operation_id,
            'user_id': self.user_id,
            'session_id': self.session_id,
            'operation_type': self.operation_type.value,
            'position': self.position,
            'length': self.length,
            'content': self.content,
            'old_content': self.old_content,
            'timestamp': self.timestamp.isoformat(),
            'version': self.version,
            'parent_version': self.parent_version,
            'metadata': self.metadata
        }


@dataclass
class ConflictInfo(BaseModel):
    """冲突信息"""
    conflict_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    operations: List[Operation] = field(default_factory=list)
    conflict_type: str = ""                 # 冲突类型
    description: str = ""                   # 冲突描述
    
    # 冲突位置
    start_position: int = 0
    end_position: int = 0
    
    # 解决方案
    resolution_strategy: ConflictResolution = ConflictResolution.AUTOMATIC
    resolved: bool = False
    resolution_result: Optional[Operation] = None
    
    # 时间信息
    detected_at: datetime.datetime = field(default_factory=datetime.datetime.now)
    resolved_at: Optional[datetime.datetime] = None


@dataclass
class UserSession(BaseModel):
    """用户会话"""
    session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    user_id: str = ""
    username: str = ""
    role: UserRole = UserRole.VIEWER
    
    # 会话状态
    status: SessionStatus = SessionStatus.ACTIVE
    last_activity: datetime.datetime = field(default_factory=datetime.datetime.now)
    connected_at: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    # 光标和选择
    cursor_position: int = 0
    selection_start: int = 0
    selection_end: int = 0
    
    # 权限
    can_edit: bool = True
    can_comment: bool = True
    can_view_history: bool = True
    
    # 网络信息
    ip_address: str = ""
    user_agent: str = ""
    
    def is_active(self, timeout_seconds: int = 300) -> bool:
        """检查会话是否活跃"""
        if self.status == SessionStatus.DISCONNECTED:
            return False
        
        time_diff = datetime.datetime.now() - self.last_activity
        return time_diff.total_seconds() < timeout_seconds
    
    def update_activity(self):
        """更新活动时间"""
        self.last_activity = datetime.datetime.now()
        if self.status == SessionStatus.IDLE:
            self.status = SessionStatus.ACTIVE


@dataclass
class DocumentState(BaseModel):
    """文档状态"""
    document_id: str = ""
    content: str = ""
    version: int = 0
    checksum: str = ""
    
    # 操作历史
    operations: List[Operation] = field(default_factory=list)
    
    # 时间信息
    created_at: datetime.datetime = field(default_factory=datetime.datetime.now)
    modified_at: datetime.datetime = field(default_factory=datetime.datetime.now)
    
    def calculate_checksum(self) -> str:
        """计算内容校验和"""
        return hashlib.md5(self.content.encode('utf-8')).hexdigest()
    
    def update_checksum(self):
        """更新校验和"""
        self.checksum = self.calculate_checksum()
    
    def apply_operation(self, operation: Operation) -> bool:
        """应用操作到文档"""
        try:
            if operation.operation_type == OperationType.INSERT:
                # 插入文本
                pos = operation.position
                self.content = self.content[:pos] + operation.content + self.content[pos:]
                
            elif operation.operation_type == OperationType.DELETE:
                # 删除文本
                pos = operation.position
                length = operation.length
                self.content = self.content[:pos] + self.content[pos + length:]
                
            elif operation.operation_type == OperationType.REPLACE:
                # 替换文本
                pos = operation.position
                length = operation.length
                self.content = self.content[:pos] + operation.content + self.content[pos + length:]
            
            # 更新版本和时间
            self.version += 1
            self.modified_at = datetime.datetime.now()
            self.update_checksum()
            
            # 记录操作
            self.operations.append(operation)
            
            return True
            
        except Exception as e:
            logger.error(f"应用操作失败: {str(e)}")
            return False


class RealtimeCollaboration(BaseComponent):
    """实时协作编辑器"""
    
    def get_required_configs(self) -> List[str]:
        """获取必需的配置项"""
        return []
    
    def _setup_component(self):
        """设置组件特定的初始化逻辑"""
        self.logger.info("实时协作编辑器初始化")
        
        # 文档状态管理
        self.documents: Dict[str, DocumentState] = {}
        
        # 用户会话管理
        self.sessions: Dict[str, UserSession] = {}
        self.user_sessions: Dict[str, Set[str]] = defaultdict(set)  # user_id -> session_ids
        
        # 操作队列和历史
        self.operation_queue: deque = deque(maxlen=10000)
        self.operation_history: Dict[str, List[Operation]] = defaultdict(list)
        
        # 冲突管理
        self.conflicts: Dict[str, ConflictInfo] = {}
        self.conflict_resolvers = {
            ConflictResolution.LAST_WRITE_WINS: self._resolve_last_write_wins,
            ConflictResolution.FIRST_WRITE_WINS: self._resolve_first_write_wins,
            ConflictResolution.MERGE: self._resolve_merge,
            ConflictResolution.AUTOMATIC: self._resolve_automatic
        }
        
        # 事件回调
        self.event_callbacks: Dict[str, List[Callable]] = defaultdict(list)
        
        # 同步锁
        self.document_locks: Dict[str, threading.RLock] = defaultdict(threading.RLock)
        self.session_lock = threading.RLock()
        
        # 配置参数
        self.max_operations_per_second = 100
        self.session_timeout = 300  # 5分钟
        self.auto_save_interval = 30  # 30秒
        self.conflict_detection_enabled = True
        
        # 启动后台任务
        self._start_background_tasks()
        
        self.logger.info("实时协作编辑器初始化完成")
    
    def create_session(self, 
                      user_id: str,
                      username: str,
                      role: UserRole = UserRole.VIEWER,
                      **kwargs) -> UserSession:
        """
        创建用户会话
        
        Args:
            user_id: 用户ID
            username: 用户名
            role: 用户角色
            **kwargs: 其他参数
            
        Returns:
            用户会话对象
        """
        try:
            with self.session_lock:
                session = UserSession(
                    user_id=user_id,
                    username=username,
                    role=role,
                    ip_address=kwargs.get('ip_address', ''),
                    user_agent=kwargs.get('user_agent', '')
                )
                
                # 设置权限
                if role == UserRole.OWNER:
                    session.can_edit = True
                    session.can_comment = True
                    session.can_view_history = True
                elif role == UserRole.EDITOR:
                    session.can_edit = True
                    session.can_comment = True
                    session.can_view_history = True
                elif role == UserRole.REVIEWER:
                    session.can_edit = False
                    session.can_comment = True
                    session.can_view_history = True
                elif role == UserRole.VIEWER:
                    session.can_edit = False
                    session.can_comment = False
                    session.can_view_history = False
                
                # 注册会话
                self.sessions[session.session_id] = session
                self.user_sessions[user_id].add(session.session_id)
                
                # 触发事件
                self._trigger_event('session_created', {
                    'session': session,
                    'user_id': user_id,
                    'username': username
                })
                
                self.logger.info(f"用户会话创建成功: {username} ({session.session_id})")
                return session
                
        except Exception as e:
            self.logger.error(f"创建用户会话失败: {str(e)}")
            raise
    
    def close_session(self, session_id: str) -> bool:
        """
        关闭用户会话
        
        Args:
            session_id: 会话ID
            
        Returns:
            是否成功关闭
        """
        try:
            with self.session_lock:
                if session_id not in self.sessions:
                    return False
                
                session = self.sessions[session_id]
                user_id = session.user_id
                
                # 更新状态
                session.status = SessionStatus.DISCONNECTED
                
                # 从用户会话集合中移除
                if user_id in self.user_sessions:
                    self.user_sessions[user_id].discard(session_id)
                    if not self.user_sessions[user_id]:
                        del self.user_sessions[user_id]
                
                # 触发事件
                self._trigger_event('session_closed', {
                    'session': session,
                    'session_id': session_id
                })
                
                # 删除会话
                del self.sessions[session_id]
                
                self.logger.info(f"用户会话关闭: {session.username} ({session_id})")
                return True
                
        except Exception as e:
            self.logger.error(f"关闭用户会话失败: {str(e)}")
            return False
    
    def create_document(self, 
                       document_id: str,
                       initial_content: str = "") -> DocumentState:
        """
        创建文档
        
        Args:
            document_id: 文档ID
            initial_content: 初始内容
            
        Returns:
            文档状态对象
        """
        try:
            with self.document_locks[document_id]:
                if document_id in self.documents:
                    raise ValueError(f"文档已存在: {document_id}")
                
                document = DocumentState(
                    document_id=document_id,
                    content=initial_content,
                    version=1
                )
                document.update_checksum()
                
                self.documents[document_id] = document
                
                # 触发事件
                self._trigger_event('document_created', {
                    'document': document,
                    'document_id': document_id
                })
                
                self.logger.info(f"文档创建成功: {document_id}")
                return document
                
        except Exception as e:
            self.logger.error(f"创建文档失败: {str(e)}")
            raise
    
    def apply_operation(self, 
                       document_id: str,
                       operation: Operation) -> bool:
        """
        应用操作到文档
        
        Args:
            document_id: 文档ID
            operation: 操作对象
            
        Returns:
            是否成功应用
        """
        try:
            with self.document_locks[document_id]:
                if document_id not in self.documents:
                    raise ValueError(f"文档不存在: {document_id}")
                
                document = self.documents[document_id]
                
                # 检查会话权限
                if not self._check_operation_permission(operation):
                    raise PermissionError("用户没有执行此操作的权限")
                
                # 检查冲突
                if self.conflict_detection_enabled:
                    conflicts = self._detect_conflicts(document_id, operation)
                    if conflicts:
                        # 处理冲突
                        resolved_operation = self._resolve_conflicts(conflicts, operation)
                        if resolved_operation:
                            operation = resolved_operation
                        else:
                            return False
                
                # 应用操作
                success = document.apply_operation(operation)
                
                if success:
                    # 添加到操作队列
                    self.operation_queue.append(operation)
                    self.operation_history[document_id].append(operation)
                    
                    # 广播操作给其他用户
                    self._broadcast_operation(document_id, operation)
                    
                    # 触发事件
                    self._trigger_event('operation_applied', {
                        'document_id': document_id,
                        'operation': operation,
                        'document': document
                    })
                    
                    self.logger.debug(f"操作应用成功: {operation.operation_type.value} 在 {document_id}")
                
                return success
                
        except Exception as e:
            self.logger.error(f"应用操作失败: {str(e)}")
            return False
    
    def get_document_state(self, document_id: str) -> Optional[DocumentState]:
        """
        获取文档状态
        
        Args:
            document_id: 文档ID
            
        Returns:
            文档状态对象
        """
        return self.documents.get(document_id)
    
    def get_active_sessions(self, document_id: str = None) -> List[UserSession]:
        """
        获取活跃会话列表
        
        Args:
            document_id: 文档ID（可选）
            
        Returns:
            活跃会话列表
        """
        try:
            with self.session_lock:
                active_sessions = []
                
                for session in self.sessions.values():
                    if session.is_active(self.session_timeout):
                        active_sessions.append(session)
                
                return active_sessions
                
        except Exception as e:
            self.logger.error(f"获取活跃会话失败: {str(e)}")
            return []
    
    def update_cursor_position(self, 
                              session_id: str,
                              position: int,
                              selection_start: int = None,
                              selection_end: int = None) -> bool:
        """
        更新光标位置
        
        Args:
            session_id: 会话ID
            position: 光标位置
            selection_start: 选择开始位置
            selection_end: 选择结束位置
            
        Returns:
            是否成功更新
        """
        try:
            with self.session_lock:
                if session_id not in self.sessions:
                    return False
                
                session = self.sessions[session_id]
                session.cursor_position = position
                
                if selection_start is not None:
                    session.selection_start = selection_start
                if selection_end is not None:
                    session.selection_end = selection_end
                
                session.update_activity()
                
                # 广播光标位置更新
                self._broadcast_cursor_update(session)
                
                return True
                
        except Exception as e:
            self.logger.error(f"更新光标位置失败: {str(e)}")
            return False    

    # 冲突检测和解决方法
    def _detect_conflicts(self, 
                         document_id: str,
                         operation: Operation) -> List[ConflictInfo]:
        """检测操作冲突"""
        conflicts = []
        
        try:
            document = self.documents[document_id]
            
            # 获取最近的操作
            recent_operations = [
                op for op in self.operation_history[document_id][-10:]
                if op.user_id != operation.user_id and
                abs((op.timestamp - operation.timestamp).total_seconds()) < 5
            ]
            
            for recent_op in recent_operations:
                conflict = self._check_operation_conflict(operation, recent_op)
                if conflict:
                    conflicts.append(conflict)
            
            return conflicts
            
        except Exception as e:
            self.logger.error(f"冲突检测失败: {str(e)}")
            return []
    
    def _check_operation_conflict(self, 
                                 op1: Operation,
                                 op2: Operation) -> Optional[ConflictInfo]:
        """检查两个操作是否冲突"""
        try:
            # 位置重叠检测
            op1_start = op1.position
            op1_end = op1.position + op1.length
            op2_start = op2.position
            op2_end = op2.position + op2.length
            
            # 检查是否有位置重叠
            if not (op1_end <= op2_start or op2_end <= op1_start):
                # 存在冲突
                conflict = ConflictInfo(
                    operations=[op1, op2],
                    conflict_type="position_overlap",
                    description=f"操作位置重叠: {op1.operation_type.value} vs {op2.operation_type.value}",
                    start_position=min(op1_start, op2_start),
                    end_position=max(op1_end, op2_end)
                )
                return conflict
            
            return None
            
        except Exception as e:
            self.logger.error(f"冲突检查失败: {str(e)}")
            return None
    
    def _resolve_conflicts(self, 
                          conflicts: List[ConflictInfo],
                          operation: Operation) -> Optional[Operation]:
        """解决冲突"""
        try:
            if not conflicts:
                return operation
            
            # 选择主要冲突（最严重的）
            main_conflict = max(conflicts, key=lambda c: c.end_position - c.start_position)
            
            # 根据策略解决冲突
            resolver = self.conflict_resolvers.get(main_conflict.resolution_strategy)
            if resolver:
                resolved_operation = resolver(main_conflict, operation)
                
                if resolved_operation:
                    main_conflict.resolved = True
                    main_conflict.resolved_at = datetime.datetime.now()
                    main_conflict.resolution_result = resolved_operation
                    
                    # 记录冲突
                    self.conflicts[main_conflict.conflict_id] = main_conflict
                    
                    # 触发事件
                    self._trigger_event('conflict_resolved', {
                        'conflict': main_conflict,
                        'original_operation': operation,
                        'resolved_operation': resolved_operation
                    })
                
                return resolved_operation
            
            return None
            
        except Exception as e:
            self.logger.error(f"冲突解决失败: {str(e)}")
            return None
    
    def _resolve_last_write_wins(self, 
                                conflict: ConflictInfo,
                                operation: Operation) -> Optional[Operation]:
        """最后写入获胜策略"""
        # 简单返回当前操作（最新的）
        return operation
    
    def _resolve_first_write_wins(self, 
                                 conflict: ConflictInfo,
                                 operation: Operation) -> Optional[Operation]:
        """首次写入获胜策略"""
        # 拒绝当前操作，保持原有内容
        return None
    
    def _resolve_merge(self, 
                      conflict: ConflictInfo,
                      operation: Operation) -> Optional[Operation]:
        """智能合并策略"""
        try:
            if len(conflict.operations) < 2:
                return operation
            
            # 获取冲突的操作
            other_op = conflict.operations[0] if conflict.operations[0] != operation else conflict.operations[1]
            
            # 简单的合并逻辑：如果都是插入操作，尝试合并内容
            if (operation.operation_type == OperationType.INSERT and 
                other_op.operation_type == OperationType.INSERT):
                
                # 创建合并后的操作
                merged_operation = Operation(
                    user_id=operation.user_id,
                    session_id=operation.session_id,
                    operation_type=OperationType.INSERT,
                    position=min(operation.position, other_op.position),
                    content=f"{other_op.content}{operation.content}",
                    version=operation.version,
                    parent_version=operation.parent_version
                )
                
                return merged_operation
            
            # 其他情况使用最后写入获胜
            return operation
            
        except Exception as e:
            self.logger.error(f"智能合并失败: {str(e)}")
            return operation
    
    def _resolve_automatic(self, 
                          conflict: ConflictInfo,
                          operation: Operation) -> Optional[Operation]:
        """自动解决策略"""
        # 根据操作类型自动选择策略
        if operation.operation_type == OperationType.INSERT:
            return self._resolve_merge(conflict, operation)
        else:
            return self._resolve_last_write_wins(conflict, operation)
    
    # 权限检查方法
    def _check_operation_permission(self, operation: Operation) -> bool:
        """检查操作权限"""
        try:
            session_id = operation.session_id
            if session_id not in self.sessions:
                return False
            
            session = self.sessions[session_id]
            
            # 检查会话是否活跃
            if not session.is_active(self.session_timeout):
                return False
            
            # 检查编辑权限
            if operation.operation_type in [OperationType.INSERT, OperationType.DELETE, OperationType.REPLACE]:
                return session.can_edit
            
            # 其他操作（如光标移动）允许所有用户
            return True
            
        except Exception as e:
            self.logger.error(f"权限检查失败: {str(e)}")
            return False
    
    # 广播方法
    def _broadcast_operation(self, document_id: str, operation: Operation):
        """广播操作给其他用户"""
        try:
            # 获取文档的所有活跃会话
            active_sessions = self.get_active_sessions()
            
            # 排除操作发起者
            target_sessions = [
                session for session in active_sessions
                if session.session_id != operation.session_id
            ]
            
            # 触发广播事件
            self._trigger_event('operation_broadcast', {
                'document_id': document_id,
                'operation': operation,
                'target_sessions': target_sessions
            })
            
        except Exception as e:
            self.logger.error(f"广播操作失败: {str(e)}")
    
    def _broadcast_cursor_update(self, session: UserSession):
        """广播光标位置更新"""
        try:
            # 获取其他活跃会话
            other_sessions = [
                s for s in self.sessions.values()
                if s.session_id != session.session_id and s.is_active(self.session_timeout)
            ]
            
            # 触发广播事件
            self._trigger_event('cursor_broadcast', {
                'session': session,
                'target_sessions': other_sessions
            })
            
        except Exception as e:
            self.logger.error(f"广播光标更新失败: {str(e)}")
    
    # 事件系统
    def register_event_callback(self, event_type: str, callback: Callable):
        """注册事件回调"""
        self.event_callbacks[event_type].append(callback)
    
    def _trigger_event(self, event_type: str, data: Dict[str, Any]):
        """触发事件"""
        try:
            callbacks = self.event_callbacks.get(event_type, [])
            for callback in callbacks:
                try:
                    callback(data)
                except Exception as e:
                    self.logger.error(f"事件回调执行失败 {event_type}: {str(e)}")
        except Exception as e:
            self.logger.error(f"触发事件失败 {event_type}: {str(e)}")
    
    # 后台任务
    def _start_background_tasks(self):
        """启动后台任务"""
        # 会话清理任务
        cleanup_thread = threading.Thread(target=self._session_cleanup_task, daemon=True)
        cleanup_thread.start()
        
        # 自动保存任务
        autosave_thread = threading.Thread(target=self._autosave_task, daemon=True)
        autosave_thread.start()
    
    def _session_cleanup_task(self):
        """会话清理任务"""
        while True:
            try:
                time.sleep(60)  # 每分钟检查一次
                
                with self.session_lock:
                    expired_sessions = []
                    
                    for session_id, session in self.sessions.items():
                        if not session.is_active(self.session_timeout):
                            expired_sessions.append(session_id)
                    
                    # 清理过期会话
                    for session_id in expired_sessions:
                        self.close_session(session_id)
                        
                    if expired_sessions:
                        self.logger.info(f"清理过期会话: {len(expired_sessions)} 个")
                        
            except Exception as e:
                self.logger.error(f"会话清理任务异常: {str(e)}")
    
    def _autosave_task(self):
        """自动保存任务"""
        while True:
            try:
                time.sleep(self.auto_save_interval)
                
                # 触发自动保存事件
                self._trigger_event('autosave', {
                    'documents': list(self.documents.keys()),
                    'timestamp': datetime.datetime.now()
                })
                
            except Exception as e:
                self.logger.error(f"自动保存任务异常: {str(e)}")
    
    # 统计和监控方法
    def get_collaboration_stats(self) -> Dict[str, Any]:
        """获取协作统计信息"""
        try:
            with self.session_lock:
                active_sessions = self.get_active_sessions()
                
                stats = {
                    'total_documents': len(self.documents),
                    'total_sessions': len(self.sessions),
                    'active_sessions': len(active_sessions),
                    'total_operations': len(self.operation_queue),
                    'total_conflicts': len(self.conflicts),
                    'resolved_conflicts': len([c for c in self.conflicts.values() if c.resolved]),
                    'users_by_role': defaultdict(int),
                    'operations_by_type': defaultdict(int),
                    'recent_activity': []
                }
                
                # 按角色统计用户
                for session in active_sessions:
                    stats['users_by_role'][session.role.value] += 1
                
                # 按类型统计操作
                for operation in list(self.operation_queue)[-100:]:  # 最近100个操作
                    stats['operations_by_type'][operation.operation_type.value] += 1
                
                # 最近活动
                recent_ops = list(self.operation_queue)[-10:]
                for op in recent_ops:
                    stats['recent_activity'].append({
                        'user_id': op.user_id,
                        'operation_type': op.operation_type.value,
                        'timestamp': op.timestamp.isoformat(),
                        'position': op.position
                    })
                
                return stats
                
        except Exception as e:
            self.logger.error(f"获取协作统计失败: {str(e)}")
            return {}
    
    def get_document_history(self, 
                           document_id: str,
                           limit: int = 100) -> List[Dict[str, Any]]:
        """获取文档操作历史"""
        try:
            if document_id not in self.operation_history:
                return []
            
            operations = self.operation_history[document_id][-limit:]
            
            history = []
            for op in operations:
                history.append({
                    'operation_id': op.operation_id,
                    'user_id': op.user_id,
                    'operation_type': op.operation_type.value,
                    'position': op.position,
                    'length': op.length,
                    'content': op.content[:100] + '...' if len(op.content) > 100 else op.content,
                    'timestamp': op.timestamp.isoformat(),
                    'version': op.version
                })
            
            return history
            
        except Exception as e:
            self.logger.error(f"获取文档历史失败: {str(e)}")
            return []
    
    def export_session_data(self, session_id: str) -> Optional[Dict[str, Any]]:
        """导出会话数据"""
        try:
            if session_id not in self.sessions:
                return None
            
            session = self.sessions[session_id]
            
            return {
                'session_info': {
                    'session_id': session.session_id,
                    'user_id': session.user_id,
                    'username': session.username,
                    'role': session.role.value,
                    'status': session.status.value,
                    'connected_at': session.connected_at.isoformat(),
                    'last_activity': session.last_activity.isoformat(),
                    'cursor_position': session.cursor_position,
                    'selection_start': session.selection_start,
                    'selection_end': session.selection_end
                },
                'permissions': {
                    'can_edit': session.can_edit,
                    'can_comment': session.can_comment,
                    'can_view_history': session.can_view_history
                },
                'network_info': {
                    'ip_address': session.ip_address,
                    'user_agent': session.user_agent
                }
            }
            
        except Exception as e:
            self.logger.error(f"导出会话数据失败: {str(e)}")
            return None